package com.bbz.core.concurrency.work8;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 循环栅栏：CyclicBarrier
 * CyclicBarrier也是一种多线程并发控制的实用工具，和CountDownLatch一样具有等待计数的功能，
 * 但是相比于CountDownLatch功能更加强大。
 * 
 * @author binbin.a.zhang
 *
 */
public class CyclicBarrierDemo {
	// 指定必须有6个运动员到达才行
	private static CyclicBarrier barrier = new CyclicBarrier(6, () -> {
		System.out.println("所有运动员入场，裁判员一声令下！！！！！");
	});

	public static void main(String[] args) {
		System.out.println("运动员准备进场，全场欢呼............");

		ExecutorService service = Executors.newFixedThreadPool(6);
		for (int i = 0; i < 6; i++) {
			service.execute(() -> {
				try {
					System.out.println(Thread.currentThread().getName() + " 运动员，进场");
					barrier.await();
					System.out.println(Thread.currentThread().getName() + "  运动员出发");
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					e.printStackTrace();
				}
			});
		}
		service.shutdown();
	}
}
